package net.ui.model.panel;

import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.digester.Digester;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

public class PanelConfig implements Serializable {

	private Map<String, PanelBean> panelMap = new HashMap<String, PanelBean>();

	private List<PanelBean> panelList = new ArrayList<PanelBean>();

	public static PanelConfig init(InputStream aConfig) throws Exception {

		Digester digester = new Digester();

		digester.setValidating(false);

		digester.addObjectCreate("panelList", PanelConfig.class);

		digester.addObjectCreate("panelList/panel", PanelBean.class);

		digester.addSetProperties("panelList/panel");

		digester.addObjectCreate("panelList/panel/element", PanelElementBean.class);

		digester.addSetProperties("panelList/panel/element");

		digester.addCallMethod("panelList/panel/element/item", "addItem", 2);

		digester.addCallParam("panelList/panel/element/item", 0, "name");

		digester.addCallParam("panelList/panel/element/item", 1, "value");

		digester.addSetNext("panelList/panel", "addPanel");

		digester.addSetNext("panelList/panel/element", "addElement");
		
		//digester.addSetNext("panelList/panel/element/item", "addItem");

		PanelConfig panelConfig = (PanelConfig) digester.parse(aConfig);

		return panelConfig;
	}

	public void addPanel(PanelBean aPanel) {
		aPanel.setPanelConfig(this);
		this.panelMap.put(aPanel.getId(), aPanel);
		this.panelList.add(aPanel);
	}

	public void removePanel(PanelBean aPanel) {
		this.panelMap.remove(aPanel.getId());
		this.panelList.remove(aPanel);
	}

	public PanelBean getPanel(String aPanelId) {

		return (PanelBean) this.panelMap.get(aPanelId);
	}

	public List<PanelBean> getPanelList() {
		return panelList;
	}

	public String toString() {
		return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).append("panelMap", panelMap).toString();
	}

}
